package cn.ad.server.persistence;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

import cn.ad.server.domain.ad.Platform;


@Repository
public class PlatformRepositoryImp implements PlatformRepository {
	
	Map<Integer,Platform> cache = new HashMap<Integer,Platform>();
	Map<String, Long> timeCache = new HashMap<String, Long>();
	
	@Resource(name = "cacheRedisTemplate")
	private ValueOperations<String, Platform> platformValueOperations;
	
	public Platform fetchPlatformById(Integer platformId) {
//		Platform platform = platformValueOperations.get(Platform.cacheKey(platformId));
//		return platform;
		return this.fetch(platformId);
	}
	
	
	Platform fetch(int pid) {
		String lastTimeKey = String.valueOf(pid) + ".time";
		long lastTimeValue = timeCache.get(lastTimeKey) == null ? 0 : timeCache.get(lastTimeKey);
		Platform value = cache.get(pid);
		//long lastTime = lastTimeValue == 0 ? System.currentTimeMillis() : lastTimeValue;
		long mDiff = (System.currentTimeMillis() - lastTimeValue) / 1000;
		if (value == null || mDiff >= 30) {
			value = platformValueOperations.get(Platform.cacheKey(pid));
			cache.put(pid, value);
			timeCache.put(lastTimeKey, System.currentTimeMillis());
		}
		return value;
	}
	
	
}
